--
-- Author: shunguo.chen
-- Date: 2018-02-07 14:08:11
--
-- MapNpcPanel 地图npc列表

local ClassRef = app.mvc.createPanelClass(...)

local GAP = 0

function ClassRef.create(node)
	local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.MapNpcNode))
	if node == nil then
		ccui.Helper:doLayout(sprite)
	end
	sprite:init()
	return sprite
end

function ClassRef:init(data)
	self.super.init(self, data)

	display.nodeRemoveForNotHit(self, function()
			if self:isVisible() then
				self:performWithDelay(function() self:setVisible(false) end, 0)
			end
		end)

	self._ui.Button_1:setPressedActionEnabled(false)
	self._btns = {self._ui.Button_1}
	self._texts = {self._ui.Text_1}

	self._panelWid = self._ui.Panel:getContentSize2()
	self._btnHeight = self._ui.Button_1:getContentSize().height
end

function ClassRef:onBtnClick(cb)
	self._onBtnClick = cb
end

function ClassRef:refreshList(npcs)
	self:setVisible(true)

	for i,v in ipairs(self._btns) do
		v:setVisible(false)
		self._texts[i]:setVisible(false)
	end

	local height = #npcs * (GAP + self._btnHeight) - GAP
	local btn, text
	for i,v in ipairs(npcs) do
		btn = self._btns[i]
		text = self._texts[i]
		if not btn then
			btn = self._btns[1]:clone()
			self._ui.Panel:addChild(btn)
			self._btns[i] = btn

			text = self._texts[1]:clone()
			self._ui.Panel:addChild(text)
			self._texts[i] = text
		end

		btn:addClickEventListener(function()
			executeFunc(self._onBtnClick, v.id)
		end)

		btn:setVisible(true)
		text:setVisible(true)

		local posY = height - self._btnHeight/2 - (self._btnHeight + GAP) * (i-1)
		btn:setPositionY(posY)
		text:setPositionY(posY)
		text:setString(v.name)
	end

	self._ui.Panel:setContentSize(cc.size(self._panelWid, height))
	ccui.Helper:doLayout(self)
end

return ClassRef